package com.adjy.pathbuilders.rendering;

import android.view.SurfaceHolder;

/**
 * GameThread object that will hold the main loop for the Game
 */
public class GameThread extends Thread {

	private SurfaceHolder surfaceHolder;
	private boolean mRun;
	private RenderingSurface msurfacePanel;
	private GameCanvas gameCanvas;

	/**
	 * Creates a GameThread
	 * 
	 * @param sholder
	 *            SurfaceHolder from the surface which the game will be rendered
	 * @param spanel
	 *            RenderingSurface which the game will be rendered
	 */
	public GameThread(SurfaceHolder sholder, RenderingSurface spanel) {
		surfaceHolder = sholder;
		mRun = false;
		msurfacePanel = spanel;
		setPriority(Thread.MAX_PRIORITY);
	}

	/**
	 * Sets the game running
	 * 
	 * @param bRun
	 *            True - Game Runs<br>
	 *            False - Stops Game
	 */
	public void setRunning(boolean bRun) {
		mRun = bRun;
	}

	@Override
	public void run() {
		super.run();
		long frameEndedTime = getCurrentTime();
		long frameCurrentTime;
		gameCanvas = new GameCanvas();
		while (mRun) {
			frameCurrentTime = getCurrentTime();
			gameCanvas.setCanvas(surfaceHolder.lockCanvas());
			if (gameCanvas.getCanvas() != null) {
				float elapsedTime = (frameCurrentTime - frameEndedTime)/1000.f;
				msurfacePanel.doDraw(gameCanvas, elapsedTime);
				surfaceHolder.unlockCanvasAndPost(gameCanvas.getCanvas());
				gameCanvas.nullfyCanvas();
			}
			frameEndedTime = frameCurrentTime;
		}
	}
	
	private long getCurrentTime() {
		return System.nanoTime()/1000000;
	}
	
}
